package com.sskj.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sskj.api.domain.ProductThingsModel;
import com.sskj.api.domain.ThingModelTemplate;
import com.sskj.api.mapper.ProductThingsModelMapper;
import com.sskj.api.service.IProductThingsModelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ProductThingsModelService extends ServiceImpl<ProductThingsModelMapper, ProductThingsModel> implements IProductThingsModelService {

    @Override
    public void add(ProductThingsModel productThingsModel) {
        ProductThingsModel productThingsModel1 = get(productThingsModel.getProductId(), productThingsModel.getTemplateId());
        if (productThingsModel1 == null) {
            productThingsModel.setCreateTime(LocalDateTime.now());
            save(productThingsModel);
        }
    }

    @Override
    public void deleteById(Long id) {
        removeById(id);
    }

    @Override
    public IPage<ThingModelTemplate> pageListByProductId(Long productId, Long pageNo, Long pageSize) {
        IPage<ProductThingsModel> pageConfig = new Page<>(pageNo, pageSize);
        return baseMapper.pageListByProductId(pageConfig, productId);
    }

    @Override
    public List<ThingModelTemplate> allByProductId(Long productId) {
        return baseMapper.allByProductId(productId);
    }

    /**
     * 获取映射关系
     * @param productId 产品ID
     * @param templateId 模板ID
     * @return 物模型
     */
    private ProductThingsModel get(Long productId, Long templateId) {
        LambdaQueryWrapper<ProductThingsModel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ProductThingsModel::getProductId, productId)
                .eq(ProductThingsModel::getTemplateId, templateId);

        return getOne(lambdaQueryWrapper);
    }
}
